<!--
 * @Author: 赵克强 huohuo625@163.com
 * @Date: 2024-08-13 14:44:57
 * @LastEditors: 赵克强 huohuo625@163.com
 * @LastEditTime: 2024-10-22 10:41:39
 * @FilePath: \hy-ui\src\views\taskMassage\components\task\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="pro-task">
    <el-container>
      <el-aside width="180px"
        ><el-menu default-active="2" class="el-menu-vertical-demo">
          <el-menu-item index="1" @click="() => handleQuery({ type: '10' })">
            <i class="el-icon-star-on" style="color: rgb(247, 186, 42)"></i>
            <span slot="title" class="subitemTitle"
              ><span>我的关注</span>
              <!-- <span class="soltNum">11</span> -->
            </span>
          </el-menu-item>
          <el-menu-item index="2" @click="() => handleQuery({ type: '1' })">
            <i class="el-icon-menu" style="color: #409eff"></i>
            <span slot="title" class="subitemTitle"
              ><span>全部任务</span>
              <!-- <span class="soltNum">99</span> -->
            </span>
          </el-menu-item>
          <el-menu-item index="8" @click="() => handleQuery({ type: '7' })">
            <i class="el-icon-time" style="color: purple"></i>
            <span slot="title" class="subitemTitle"
              ><span>即将逾期</span>
              <!-- <span class="soltNum">99</span> -->
            </span>
          </el-menu-item>
          <el-menu-item index="9" @click="() => handleQuery({ type: '8' })">
            <i class="el-icon-warning" style="color: #f56c6c"></i>
            <span slot="title" class="subitemTitle"
              ><span>逾期任务</span>
              <!-- <span class="soltNum">99</span> -->
            </span>
          </el-menu-item>
          <el-menu-item index="10" @click="() => handleQuery({ type: '9' })">
            <i class="el-icon-circle-check" style="color: #67c23a"></i>
            <span slot="title" class="subitemTitle"
              ><span>已完成</span>
              <!-- span class="soltNum">99</span> -->
            </span>
          </el-menu-item>
        </el-menu></el-aside
      >
      <el-main
        v-loading="loading"
        :style="{ background: activeName === '1' ? '#edeff0' : '#fff' }"
      >
        <div>
          <div class="taskHeader">
            <div>
              <el-button
                type="primary"
                @click="() => handleTask('standard')"
                size="mini"
                ><i class="el-icon-plus" style="margin-right: 3px"></i
                >任务</el-button
              >
              <el-button type="primary" @click="handleAddTaskList" size="mini"
                ><i class="el-icon-plus" style="margin-right: 3px"></i
                >新建清单</el-button
              >
            </div>
            <div style="display: flex; align-items: center">
              <el-radio-group
                style="margin-right: 20px"
                v-model="viewFormat"
                size="mini"
                v-if="activeName === '5'"
                @input="handleViewFormatChange"
              >
                <!-- <el-radio-button label="hour">时</el-radio-button> -->
                <el-radio-button label="day">天</el-radio-button>
                <el-radio-button label="month">月</el-radio-button>
                <el-radio-button label="year">年</el-radio-button>
              </el-radio-group>
              <el-button
                type="text"
                @click="handleQuery"
                style="margin-right: 20px"
                >刷新<i
                  class="el-icon-refresh-right"
                  style="margin-left: 5px"
                ></i
              ></el-button>
              <el-dropdown
                trigger="click"
                style="margin-right: 30px"
                placement="bottom-end"
              >
                <span class="el-dropdown-link">
                  {{ screenTitle
                  }}<i class="el-icon-arrow-down el-icon--right"></i>
                </span>
                <el-dropdown-menu slot="dropdown" style="width: 150px">
                  <el-dropdown-item
                    v-for="item in grounpModeList"
                    :key="item.value"
                    v-show="!(item.value === '6' && activeName === '5')"
                    ><div
                      @click="handleDropClick(item)"
                      style="
                        display: flex;
                        align-items: center;
                        justify-content: space-between;
                      "
                    >
                      <span>{{ item.label }}</span
                      ><i
                        class="el-icon-check"
                        v-show="grounpModeValue === item.value"
                      ></i></div
                  ></el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <el-badge
                :value="viewList.length && viewList.length"
                v-if="screenShow"
              >
                <screen
                  :title="screenTitle"
                  :type="grounpModeValue"
                  ref="screenRef"
                  :handleScreenSubmit="handleScreenSubmit"
                  :getList="getList"
                />
              </el-badge>
              <span style="padding-left: 20px"
                ><moreOperate :getOperateParams="getOperateParams"
              /></span>
            </div>
          </div>
          <div>
            <bulletinBoard
              :propsData="{
                list,
                viewList,
                openTaskDrawer,
                handleTaskEdit,
                handleTaskDelete,
                grounpModeValue,
                handleOperateList,
                handleTask,
                getList,
              }"
              v-if="list && list.length && activeName === '1' && !loading"
            />
            <tableMode
              :propsData="{
                list,
                viewList,
                openTaskDrawer,
                handleTaskEdit,
                handleTaskDelete,
              }"
              v-if="list && list.length && activeName === '2' && !loading"
            />
            <ganttChart
              :propsData="{
                list,
                viewList,
                openTaskDrawer,
                handleTaskEdit,
                handleTaskDelete,
                grounpModeValue,
                isProject: true,
              }"
              v-if="list.length && activeName === '5'"
              ref="ganttChartRef"
              :viewFormat="viewFormat"
            />
            <el-empty v-if="!list.length" description="暂无任务"></el-empty>
          </div>
        </div>
      </el-main>
    </el-container>
    <taskModel
      ref="taskModel"
      v-if="visible"
      :visible="visible"
      :close="() => (visible = false)"
      :propsObj="taskObjProps"
      :projectRow="row"
      :proList="proList"
    />
    <taskDrawer
      ref="taskDrawer"
      v-if="visibleDrawer"
      :visible="visibleDrawer"
      :close="taskDrawerClose"
      :propsObj="taskObjProps"
      :finishLoading="finishLoading"
      :handleFinishTask="handleFinishTask"
    />
    <el-dialog
      title="创建清单"
      :visible.sync="listOpen"
      v-if="listOpen"
      width="30%"
      :before-close="() => (listOpen = false)"
    >
      <el-form
        :model="listForm"
        :rules="rules"
        ref="listFormRef"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="清单名称" prop="name">
          <el-input
            v-model="listForm.name"
            placeholder="请输入清单名称"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item label="颜色" prop="color">
          <el-color-picker
            v-model="listForm.color"
            show-alpha
            :predefine="[
              '#ff4500',
              '#ff8c00',
              '#ffd700',
              '#90ee90',
              '#00ced1',
              '#1e90ff',
              '#c71585',
              'rgba(255, 69, 0, 0.68)',
              'rgb(255, 120, 0)',
              'hsv(51, 100, 98)',
              'hsva(120, 40, 94, 0.5)',
              'hsl(181, 100%, 37%)',
              'hsla(209, 100%, 56%, 0.73)',
              '#c7158577',
            ]"
          >
          </el-color-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="() => (listOpen = false)">取 消</el-button>
        <el-button type="primary" @click="createListSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script >
import screen from "@/views/taskMassage/components/task/components/screen.vue";
import moreOperate from "@/views/taskMassage/components/task/components/moreOperate.vue";
import taskModel from "@/views/taskMassage/components/task/components/taskModel.vue";
import taskDrawer from "@/views/taskMassage/components/task/components/taskDrawer.vue";
import bulletinBoard from "@/views/taskMassage/components/task/components/bulletinBoard.vue";
import tableMode from "@/views/taskMassage/components/task/components/tableMode.vue";
import ganttChart from "@/views/taskMassage/components/task/components/ganttChart.vue";
import { uuid } from "vue-uuid";
import moment from "moment";

import {
  getTaksList,
  getTaskDetail,
  deleteTask,
  finishTask,
  auditCheck,
} from "@/api/task/task.js";
import { createList, deleteList } from "@/api/task/project.js";
export default {
  components: {
    screen,
    moreOperate,
    taskModel,
    bulletinBoard,
    tableMode,
    taskDrawer,
    ganttChart,
  },
  props: {
    activeName: {
      type: String,
      default: "1",
    },
    row: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      viewFormat: "day",
      proList: {},
      list: [],
      rules: {
        name: [{ required: true, message: "请输入清单名称", trigger: "blur" }],
        color: [{ required: true, message: "请选择颜色", trigger: "change" }],
      },
      listForm: {
        color: "rgba(255, 69, 0, 0.68)",
      },
      listOpen: false,
      taskObjProps: null,
      visible: false,
      screenTitle: "清单",
      screenShow: false,
      loading: false,
      viewList: [],
      visibleDrawer: false,
      finishLoading: false,
      queryParmas: {
        type: "1",
        showType: "2",
        orderType: "2",
      },
      grounpModeValue: "10",
      grounpModeList: [
        {
          label: "清单",
          value: "10",
        },
        {
          label: "状态",
          value: "4",
        },
        {
          label: "标签",
          value: "6",
        },
        {
          label: "负责人",
          value: "7",
        },
        {
          label: "优先级",
          value: "8",
        },
        {
          label: "开始时间",
          value: "9",
        },
      ],
    };
  },
  watch: {
    activeName: {
      handler(val) {
        this.list = [];
        if (val === "1" || val === "5") {
          this.screenTitle = "清单";
          this.grounpModeValue = "10";
          this.queryParmas.groupType = "list";
          this.getList();
        }
        if (val === "2") {
          this.screenTitle = "状态";
          this.grounpModeValue = "4";
          this.queryParmas.groupType = "status";
          this.getList();
        }
      },
      deep: true,
      immediate: true,
    },
  },
  methods: {
    handleViewFormatChange() {
      this.$refs.ganttChartRef.loadData();
    },
    async reset() {
      if (this.activeName === "1" || this.activeName === "5") {
        this.screenTitle = "清单";
        this.grounpModeValue = "10";
        this.queryParmas = {
          type: "1",
          showType: "2",
          orderType: "2",
          groupType: "list",
        };
        await this.getList();
      }
      if (this.activeName === "2") {
        this.screenTitle = "状态";
        this.grounpModeValue = "4";
        this.queryParmas = {
          type: "1",
          showType: "2",
          orderType: "2",
          groupType: "status",
        };
        await this.getList();
      }
    },
    handleOperateList(val, row) {
      if (val === "1") {
        this.listOpen = true;
        this.listForm = {
          color: row.color,
          id: row.id,
          name: row.type,
        };
      } else {
        this.$confirm("确认删除该清单吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async () => {
            const res = await deleteList(row.id);
            if (res.code === 200) {
              this.$message.success("删除成功");
              this.getList();
            }
          })
          .catch(() => {});
      }
    },
    handleAddTaskList() {
      this.listOpen = true;
      this.listForm = {
        color: "rgba(255, 69, 0, 0.68)",
      };
    },
    createListSubmit() {
      this.$refs["listFormRef"].validate(async (valid) => {
        if (valid) {
          const res = await createList(this.row.id, this.listForm);
          if (res.code === 200) {
            this.$message.success("操作成功！");
            this.listOpen = false;
            this.getList();
          }
        }
      });
    },
    taskDrawerClose() {
      this.$confirm("确认关闭操作吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.visibleDrawer = false;
        })
        .catch(() => {});
    },
    async handleFinishTask(id) {
      this.$prompt("确认完成该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info",
        inputPlaceholder: "请输入备注",
        inputType: "textarea",
      })
        .then(async ({ value }) => {
          this.finishLoading = true;
          const res = await finishTask(id, { remark: value });
          this.finishLoading = false;
          if (res.code === 200) {
            this.$message.success("操作成功！");
            this.visibleDrawer = false;
            this.getList();
          }
        })
        .catch(() => {});
    },
    async handleTaskDelete(id) {
      this.$confirm("确认删除该任务吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteTask(id);
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.getList();
          }
        })
        .catch(() => {});
    },
    async handleTaskEdit(type, id) {
      const res = await getTaskDetail(id);
      const detailData = {};
      detailData.title = res.data.title;
      detailData.id = res.data.id;
      detailData.projectId = res.data.projectId;
      detailData.projectTile = res.data.projectTile;
      detailData.projectListId = res.data.projectListId;
      detailData.projectListName = res.data.projectListName;
      detailData.taskHead = [
        {
          nickName: res.data.headUserName,
          userId: res.data.headUserId,
          avatar: res.data.headUserAvatar,
          dept: { deptName: res.data?.headUserDept },
        },
      ];
      detailData.time = [res.data.startTime, res.data.endTime];
      detailData.circulateType = res.data.loopType;
      detailData.taskDescribe = res.data.description;
      if (res.data.participateInUsers?.length) {
        res.data.participateInUsers.forEach((item) => {
          item.nickName = item.name;
          item.userId = item.id;
        });
      }
      detailData.participants = res.data.participateInUsers;
      detailData.reviewType = res.data.auditUserType;
      detailData.label = res.data.tags;
      detailData.priority = res.data.priority;
      detailData.planWorking = this.handleEndTimeChange(
        res.data.startTime,
        res.data.endTime
      );
      if (res.data.auditUsers?.length) {
        res.data.auditUsers.forEach((item) => {
          item.nickName = item.name;
          item.userId = item.id;
        });
      }
      detailData.finishReview = res.data.auditUsers;
      if (res.data.copyOfUsers?.length) {
        res.data.copyOfUsers.forEach((item) => {
          item.nickName = item.name;
          item.userId = item.id;
        });
      }
      detailData.ccTo = res.data.copyOfUsers;
      if (res.data.checkOptions) {
        let data = res.data.checkOptions.split(",");
        let resetData = [];
        data.forEach((item) => {
          resetData.push({ h5Uid: uuid.v1(), content: item });
        });
        detailData.checkList = resetData;
      } else {
        detailData.checkList = [];
      }
      if (res.data.childTasks?.length) {
        res.data.childTasks.forEach((item) => {
          item.h5Uid = uuid.v1();
          item.time = [res.data.startTime, item.endTime];
          item.userId = item.id;
          item.id = item.id;
          item.taskHead = [
            {
              nickName: item.headUserName,
              userId: item.headUserId,
              avatar: item.headUserAvatar,
              dept: { deptName: item.headUserDept },
            },
          ];
        });
      }
      detailData.children = res.data.childTasks;
      detailData.fileList = res.data.files;
      this.taskObjProps = {
        type: type === "1" ? "standard" : "flow",
        getList: this.getList,
        taskDetailData: detailData,
      };
      this.visible = true;
    },
    handleEndTimeChange(start, end) {
      if (start && end) {
        let startTime = moment(start);
        let endTime = moment(end);
        let diff = endTime.diff(startTime, "milliseconds");
        let days = diff / (1000 * 60 * 60 * 24);
        return Math.round(days * 10) / 10;
      }
    },
    async openTaskDrawer(type, id, isAgain) {
      const res = await getTaskDetail(id);
      const checkRes = await auditCheck(id);
      this.taskObjProps = {
        type: type === "1" ? "standard" : "flow",
        getList: this.getList,
        taskDetailData: res.data,
        checkData: checkRes.data,
      };
      if (isAgain) return;
      this.visibleDrawer = true;
    },
    getOperateParams(params) {
      this.queryParmas = { ...this.queryParmas, ...params };
      this.getList();
    },
    handleScreenSubmit(list, isPeopleMore) {
      if (isPeopleMore) {
        // this.viewList = [];
        this.queryParmas = {
          ...this.queryParmas,
          userIds: list.length ? list.toString() : undefined,
        };
        this.$refs?.screenRefProple?.handleCancel();
        this.getList();
      } else {
        this.viewList = list;
        this.$refs.screenRef.handleCancel();
      }
    },
    handleQuery(params) {
      this.queryParmas = { ...this.queryParmas, ...params };
      this.getList();
      if (this.grounpModeValue === "9") {
        this.$refs.screenRef.getDateList({
          type: this.queryParmas.type,
          projectId: this.row.id,
        });
      }
    },
    async getList(params) {
      this.loading = true;
      const res = await getTaksList({
        ...this.queryParmas,
        ...params,
        projectId: this.row?.id,
      });
      if (res.code === 200) {
        this.list = res.data || [];
      }
      this.loading = false;
    },
    handleDropClick(value) {
      this.viewList = [];
      this.screenShow = false;
      this.screenTitle = "";
      this.queryParmas.groupType = undefined;
      this.grounpModeValue = value.value;
      const menuItem = {
        4: "status",
        6: "tag",
        7: "headUser",
        8: "priority",
        9: "startTime",
        10: "list",
      };
      this.queryParmas = {
        ...this.queryParmas,
        groupType: menuItem[value.value],
      };
      this.screenTitle = value.label;
      if (["6", "7", "9"].includes(value.value)) {
        this.screenShow = true;
        if (value.value === "9") {
          setTimeout(() => {
            this.$refs.screenRef.getDateList({
              type: this.queryParmas.type,
              projectId: this.row?.id,
            });
          }, 200);
        }
      }
      this.getList();
    },
    handleTask(type, proList) {
      this.taskObjProps = {
        type,
        getList: this.getList,
      };
      this.proList = proList;
      this.visible = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.pro-task {
  min-height: 72vh;
}
aside {
  padding: 0;
}
::v-deep .el-menu {
  min-height: 72vh;
}
.soltNum {
  color: #999;
  border: 1px solid #999;
  border-radius: 50%;
  font-size: 12px;
  line-height: 18px;
  text-align: center;
  display: inline-block;
  min-width: 18px;
  min-height: 18px;
}
.subitemTitle {
  display: inline-flex;
  justify-content: space-between;
  align-items: center;
  width: 90%;
  padding-right: 12px;
}
.el-main {
  max-height: 72vh;
  padding: 0;
  background: #edeff0;
}
.el-container {
  min-height: 72vh;
}
.taskHeader {
  background: #fff;
  padding: 5px 20px;
  display: flex;
  justify-content: space-between;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
}
.el-icon-arrow-down {
  font-size: 16px;
  color: #1890ff;
}
::v-deep .el-menu-item {
  height: 50px;
  line-height: 50px;
}
::v-deep .el-badge__content.is-fixed {
  top: 9px;
}
</style>